import type { RouteRecordRaw } from "vue-router";
import router from "./index";
import { isEmpty, isNull } from "lodash-es";

const modules = import.meta.glob("../views/**/*.vue");

/**
 * 加载路由到layout目录下
 * @param menu
 */
export function loadRoutes() {
  const userStore = useUserStore();
  const userMenu = userStore.menu as [];
  if (userMenu.length > 0) {
    const list = formatRoutes(userMenu);
    list.forEach(item => {
      if (!isNull(item.path) && !isEmpty(item.path)) {
        router.addRoute("layout", item);
      }
    });
  }
}

/**
 * 格式化路由数据
 * @param menu
 */
export function formatRoutes(menu: Array<TreeNode>): Array<RouteRecordRaw> {
  let aRouter: Array<RouteRecordRaw> = [];

  menu.forEach((oMenu: TreeNode) => {
    const item = oMenu.item;
    if (!router.hasRoute(item.componentName)) {
      if (!isNull(item.componentPath)) {
        const oRouter = {
          path: item.path,
          name: item.componentName,
          meta: {
            title: item.menuName
          },
          component: modules[`../views/${item.componentPath}.vue`]
        };
        aRouter.push(oRouter);
      }
    }

    if (oMenu.children != undefined && oMenu.children.length > 0) {
      aRouter = aRouter.concat(...formatRoutes(oMenu.children));
    }
  });

  return aRouter;
}
